/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatsoft.client.buz;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;

/**
 *
 * @author VinhThien
 */
public class ReveiveFileBusiness extends Thread {

    Socket sock;
    File file;
    public ReveiveFileBusiness(Socket socke, File f) {
        sock = socke;
        file = f;
    }

    @Override
    public void run() {
        try {
            int filesize = 6022386; // filesize temporary hardcoded 


            int bytesRead;
            int current = 0;

            // receive file 
            byte[] mybytearray = new byte[filesize];
            InputStream is = sock.getInputStream();

            bytesRead = is.read(mybytearray, 0, mybytearray.length);
            current = bytesRead;

            // thanks to A. Cádiz for the bug fix 
            do {
                bytesRead =
                        is.read(mybytearray, current, (mybytearray.length - current));
                if (bytesRead >= 0) {
                    current += bytesRead;
                }
            } while (bytesRead > -1);

            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(mybytearray, 0, current);
            bos.flush();
            System.out.println("my");

            bos.close();
            sock.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
